package cn.yotta.user.core.server.configuration;

import cn.yotta.user.api.params.login.LoginByUsernamePasswordRequest;
import cn.yotta.user.core.server.iface.login.LoginProvider;
import cn.yotta.user.core.server.iface.login.LoginUserContext;
import cn.yotta.user.core.server.iface.login.PasswordEncoder;
import cn.yotta.user.core.server.iface.login.impl.DefaultPasswordEncoder;
import cn.yotta.user.core.server.iface.login.impl.RedisLoginUserContext;
import cn.yotta.user.core.server.iface.login.impl.UsernamePasswordLoginProvider;
import cn.yotta.user.core.server.iface.token.JwyTokenGenerateStrategy;
import cn.yotta.user.core.server.iface.token.TokenGenerateStrategy;
import cn.yotta.user.core.server.manager.captcha.CaptchaManager;
import cn.yotta.user.core.server.manager.user.UserManager;
import cn.yotta.user.core.server.properties.CaptchaProperties;
import cn.yotta.user.core.server.properties.LoginTokenExpireTimeProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;


/**
 * @author wyaoyao
 * @date 2022/11/12 21:00
 */
@Configuration
@EnableConfigurationProperties({LoginTokenExpireTimeProperties.class})
public class LoginAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return new DefaultPasswordEncoder();
    }


    @Bean("usernamePasswordLoginProvider")
    @ConditionalOnMissingBean
    public LoginProvider<LoginByUsernamePasswordRequest> usernamePasswordLoginProvider(UserManager userManager,
                                                                                       CaptchaManager captchaManager,
                                                                                       PasswordEncoder passwordEncoder,
                                                                                       CaptchaProperties captchaProperties) {
        return new UsernamePasswordLoginProvider(userManager, captchaManager, passwordEncoder, captchaProperties.getEnableMock());
    }
    /**
     * 仅仅支持jwtToken
     */
    @Bean
    @ConditionalOnMissingBean(TokenGenerateStrategy.class)
    public TokenGenerateStrategy tokenGenerateStrategy() {
        return new JwyTokenGenerateStrategy();
    }



    @Bean
    @ConditionalOnBean(StringRedisTemplate.class)
    public LoginUserContext redisLoginUserContext(StringRedisTemplate redisTemplate,
                                             ObjectMapper objectMapper) {
        return new RedisLoginUserContext(redisTemplate,objectMapper);
    }
}


